package celiasoft.itasalib.query.resultparser;

import java.util.ArrayList;
import java.util.List;

import org.htmlcleaner.TagNode;

public class HTMLParsingHandler {

	public static List<TagNode> getLinksListByClass(TagNode root,
			String className) {
		
		return getElementListByClass(root, "a", new String[]{className});
		/*
		List<TagNode> linkList = new ArrayList<TagNode>();

		TagNode linkElements[] = root.getElementsByName("a", true);
		for (int i = 0; linkElements != null && i < linkElements.length; i++) {

			String classType = linkElements[i].getAttributeByName("class");

			if (classType != null && classType.equals(className)) {
				linkList.add(linkElements[i]);
			}
		}

		return linkList;*/
	}

	public static TagNode getTableByClass(TagNode root, String className) {
		return getElementByClass(root, "table", className);
	}
	
	public static TagNode getElementByClass(TagNode root, String elementType, String className) {
		TagNode el = null;

		TagNode elements[] = root.getElementsByName(elementType, true);
		for (int i = 0; elements != null && i < elements.length; i++) {
			String classType = elements[i].getAttributeByName("class");

			if (classType != null && classType.equals(className)) {
				return elements[i];
			}
		}

		return el;
	}

	public static List<TagNode> getElementListByClass(TagNode root,
			String elementType, String[] strings) {

		List<TagNode> list = new ArrayList<TagNode>();

		TagNode tableElements[] = root.getElementsByName(elementType, true);
		for (int i = 0; tableElements != null && i < tableElements.length; i++) {
			String classType = tableElements[i].getAttributeByName("class");

			if (classType != null && checkAllString(classType, strings)) {
				list.add(tableElements[i]);
			}
		}

		return list;
	}

	private static boolean checkAllString(String value, String[] check) {

		for (int i = 0; i < check.length; i++) {
			if (check[i].equals(value))
				return true;
		}

		return false;

	}

}
